﻿using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Web;

namespace Rajon {

    /// <summary>
    /// Helper class to dela with RAJON REST headers.
    /// </summary>
    public class RajonRequest {

 

        /// <summary>
        /// Gets the page size.
        /// </summary>
        public static int PageSize {
            get {
                int pgSize = 0;
                int.TryParse(System.Web.HttpContext.Current.Request.Headers["rajonPageSize"], out pgSize);
                return pgSize;
            }
        }

        /// <summary>
        /// Gests the page number.
        /// </summary>
        public static int PageNumber {
            get {
                int pgNumber = 0;                
                int.TryParse(System.Web.HttpContext.Current.Request.Headers["rajonPageNumber"], out pgNumber);
                return pgNumber;
            }
        }

        /// <summary>
        /// Manually, sets the total count of items whenusing paging.
        /// </summary>
        /// <param name="count"></param>
        public static void SetPageItemsTotalCount(int count) {            
            WebOperationContext.Current.OutgoingResponse.Headers.Add("rajonItemsTotalCount", count.ToString());            
        }

        /// <summary>
        /// Returns a paged collection according the rajon headers parameters at the request.
        /// </summary>
        /// <typeparam name="TSource"></typeparam>
        /// <param name="source">The collection to be paged</param>
        /// <returns>Only the items of the current page of the collection</returns>
        public static IEnumerable<TSource> Page<TSource>(IEnumerable<TSource> source) {
            if (PageSize == 0)
                return source;
            SetPageItemsTotalCount(source.Count());
            return source.Skip((PageNumber - 1) * PageSize).Take(PageSize);
        }

        /// <summary>
        /// Returns a paged collection according the rajon headers parameters at the request.
        /// </summary>
        /// <typeparam name="TSource"></typeparam>
        /// <param name="source">The collection to be paged</param>
        /// <returns>Only the items of the current page of the collection</returns>
        public static IQueryable<TSource> Page<TSource>(IQueryable<TSource> source) {            
            if (PageSize == 0)
                return source;
            SetPageItemsTotalCount(source.Count());            
            return source.Skip((PageNumber - 1) * PageSize).Take(PageSize);
        }

    }
     

}